package com.genreate.util.xyzw;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

// 战斗系统
class BattleSystem {
    List<Hero> team1;
    List<Hero> team2;
    int maxRounds = 15;
    int currentRound = 0;

    public BattleSystem(List<Hero> team1, List<Hero> team2) {
        this.team1 = team1;
        this.team2 = team2;
    }

    // 初始化战斗
    public void initBattle() {
        // 触发所有武将的战斗开始被动
        for (Hero hero : team1) {
            hero.onBattleStart();
        }
        for (Hero hero : team2) {
            hero.onBattleStart();
        }
    }

    // 根据速度排序
    private List<Hero> getActionOrder() {
        List<Hero> allHeroes = new ArrayList<>();
        allHeroes.addAll(team1);
        allHeroes.addAll(team2);

        // 过滤掉已死亡的英雄
        allHeroes.removeIf(hero -> !hero.isAlive);

        // 按速度排序 (加上临时速度加成)
        allHeroes.sort((h1, h2) -> Integer.compare(
                (h2.speed + h2.tempSpeedBonus),
                (h1.speed + h1.tempSpeedBonus)
        ));

        return allHeroes;
    }

    // 获取可攻击的目标
    private List<Hero> getAvailableTargets(Hero attacker, List<Hero> enemyTeam) {
        List<Hero> targets = new ArrayList<>();

        // 优先攻击前排
        for (Hero hero : enemyTeam) {
            if (hero.isAlive && (hero.position == Position.FRONT_LEFT || hero.position == Position.FRONT_RIGHT)) {
                targets.add(hero);
            }
        }

        // 如果前排没有目标，攻击后排
        if (targets.isEmpty()) {
            for (Hero hero : enemyTeam) {
                if (hero.isAlive) {
                    targets.add(hero);
                }
            }
        }

        return targets;
    }

    // 执行一个回合
    public void executeRound() {
        currentRound++;
        System.out.println("\n=== 第 " + currentRound + " 回合 ===");

        System.out.println("我方存活武将：" + team1.stream().filter(e -> e.isAlive).map(e -> e.name).collect(Collectors.joining(",")) + "\n");
        System.out.println("敌方存活武将：" + team2.stream().filter(e -> e.isAlive).map(e -> e.name).collect(Collectors.joining(",")) + "\n");
        // 回合开始处理
        for (Hero hero : team1) {
            if (hero.isAlive) {
                hero.onRoundStart();
            }
        }
        for (Hero hero : team2) {
            if (hero.isAlive) {
                hero.onRoundStart();
            }
        }

        List<Hero> actionOrder = getActionOrder();

        for (Hero attacker : actionOrder) {
            if (!attacker.isAlive) {
                continue;
            }

            // 检查控制状态
            if (attacker.controlStatus == ControlStatus.STUN || attacker.controlStatus == ControlStatus.FREEZE) {
                System.out.println(attacker.name + " 处于" + attacker.controlStatus.name() + "状态，无法行动");
                continue;
            }

            // 确定攻击目标
            List<Hero> enemyTeam = team1.contains(attacker) ? team2 : team1;
            List<Hero> availableTargets = getAvailableTargets(attacker, enemyTeam);

            if (availableTargets.isEmpty()) {
                System.out.println("没有可攻击的目标!");
                continue;
            }

            // 随机选择目标
            Random rand = new Random();
            Hero target = availableTargets.get(rand.nextInt(availableTargets.size()));

            // 随机选择普通攻击或技能攻击 (如果未被沉默)
            if (attacker.controlStatus == ControlStatus.SILENCE || rand.nextBoolean()) {
                // 普通攻击
                int damage = attacker.normalAttack();

                // 暴击判断
                if (attacker.isCriticalHit()) {
                    float critMultiplier = attacker.getCritDamageMultiplier();
                    damage *= critMultiplier;
                    System.out.println("暴击! 伤害倍率: " + critMultiplier);
                }

                // 目标受到伤害
                target.takeDamage(attacker, damage);
            } else {
                // 使用主动技能
                attacker.useActiveSkill(availableTargets);
            }

            // 检查战斗是否结束
            if (isBattleOver()) {
                return;
            }
        }

        // 回合结束清除控制效果
        for (Hero hero : team1) {
            if (hero.isAlive) {
                hero.clearControlEffects();
            }
        }
        for (Hero hero : team2) {
            if (hero.isAlive) {
                hero.clearControlEffects();
            }
        }
    }

    // 检查战斗是否结束
    public boolean isBattleOver() {
        boolean team1AllDead = team1.stream().noneMatch(hero -> hero.isAlive);
        boolean team2AllDead = team2.stream().noneMatch(hero -> hero.isAlive);

        if (team1AllDead) {
            System.out.println("敌方队伍获胜!");
            return true;
        }

        if (team2AllDead) {
            System.out.println("我方队伍获胜!");
            return true;
        }

        if (currentRound > maxRounds) {
            System.out.println("战斗超时，我方队伍失败!");
            return true;
        }

        return false;
    }

    // 开始战斗
    public void startBattle() {
        System.out.println("战斗开始!");
        initBattle();

        while (!isBattleOver()) {
            executeRound();
        }
    }
}
